Type.registerNamespace("DNNDev.DNNModules.NewsBeast");

DNNDev.DNNModules.NewsBeast.ItemViewModel = function (model) {
    var self = this;
    self.ModuleId = model.ModuleId;
    self.ItemId = model.ItemId;
    self.Title = ko.observable(model.Title);
    self.Content = ko.observable(model.Content);
    self.CreatedOnDate = ko.observable(model.CreatedOnDate);
    self.CreatedByUserID = ko.observable(model.CreatedByUserID);
    self.LastModifiedOnDate = ko.observable(model.LastModifiedOnDate);
    self.LastModifiedByUserID = ko.observable(model.LastModifiedByUserID);
};

DNNDev.DNNModules.NewsBeast.NewsletterViewModel = function (model) {
    var self = this;
    self.ID = model.ID;
    self.ID_Template = model.ID_Template;
    self.Subject = ko.observable(model.Subject);
    self.Date = ko.observable(model.Date);
    self.Send = ko.observable(model.Send);
};

DNNDev.DNNModules.NewsBeast.ViewModel = function (model, serviceClient) {
    var self = this;

    self.headers = [
        { title: '', sortPropertyName: '', asc:true },
        { title: 'Subject', sortPropertyName: 'Subject', asc: true },
        { title: 'Date', sortPropertyName: 'Date', asc: true },
        { title: 'Send', sortPropertyName: 'Send', asc: true }
    ];

    self.Items = ko.observableArray(
        ko.utils.arrayMap(model, function(item) {
            return new DNNDev.DNNModules.NewsBeast.NewsletterViewModel(item);
        })).extend({ paging: 20 });

    self.addNewsletter = function (item) {
        console.log("New Newsletter ");
        var newItem = new DNNDev.DNNModules.NewsBeast.NewsletterViewModel({
            ID: -1,
            ID_Template: " ",
            Subject: " ",
            Date: null,
            Send: false
        });
        self.Items.push(newItem);
        self.editItem(newItem);
    };

    self.saveEditNewsletter = function (item) {
        if (item.ID === -1) {
            serviceClient.insertNewsletter(item)
                .done(function (newItem) {
                    item.ID = newItem.ID;
                    item.ID_Template = newItem.ID_Template;
                    item.Subject(newItem.Subject);
                    item.Date(newItem.Date);
                    item.Send(newItem.Send);
                    self.Items.moveLast();
                    self.showEditor(false);
                });
        } else {
            serviceClient.updateNewsletter(item)
               .done(function (updItem) {
                   self.showEditor(false);
               });
        }

    };

    self.cancelEditNewsletter = function (item) {
        if (item.ItemId === -1) {
            self.Items.remove(item);
        } else {
            item.ID_Template = self.OriginalItem().ID_Template;
            item.Subject(self.OriginalItem().Subject);
            item.Date(self.OriginalItem().Date);
            item.Send(self.OriginalItem().Send);
        }
        self.showEditor(false);
    };

    self.deleteNewsletter = function (item) {
        console.log("Delete " + item.ID + " (" + item.Subject() + ")");
        serviceClient.deleteNewsletter(item)
            .done(function () {
                self.Items.remove(item);
            });
    };

    self.hasRecords = ko.computed(function () {
        return self.Items().length > 0;
    });

    self.OriginalItem = ko.observable();
    self.SelectedItem = ko.observable();
    self.showEditor = ko.observable(false);

    self.addItem = function(item, moduleId) {
        console.log("New Item ");
        var newItem = new DNNDev.DNNModules.NewsBeast.ItemViewModel({
            ModuleId: moduleId,
            ItemId: -1,
            Title: " ",
            Content: " ",
            CreatedOnDate: null,
            CreatedByUserID: -1,
            LastModifiedOnDate: null,
            LastModifiedByUserID: -1
        });
        self.Items.push(newItem);
        self.editItem(newItem);
    };

    self.editItem = function(item) {
        self.SelectedItem(item);
        self.OriginalItem(ko.toJS(item));
        self.showEditor(true);
    };

    self.deleteItem = function (item) {
        console.log("Delete " + item.ID + " (" + item.Subject() + ")");
        serviceClient.deleteItem(item)
            .done(function () {
                self.Items.remove(item);
            });
    };

    self.saveEdit = function(item) {
        if (item.ItemId === -1) {
            serviceClient.insertItem(item)
                .done(function (newItem) {
                    item.ItemId = newItem.ItemId;
                    item.CreatedOnDate(newItem.CreatedOnDate);
                    item.CreatedByUserID(newItem.CreatedByUserID);
                    item.LastModifiedOnDate(newItem.LastModifiedOnDate);
                    item.LastModifiedByUserID(newItem.LastModifiedByUserID);
                    self.Items.moveLast();
                    self.showEditor(false);
                });
        } else {
             serviceClient.updateItem(item)
                .done(function (updItem) {
                    item.LastModifiedOnDate(updItem.LastModifiedOnDate);
                    item.LastModifiedByUserID(updItem.LastModifiedByUserID);
                    self.showEditor(false);
                });
        }

    };

    self.cancelEdit = function (item) {
        if (item.ItemId === -1) {
            self.Items.remove(item);
        } else {
            item.Title(self.OriginalItem().Title);
            item.Content(self.OriginalItem().Content);
            item.CreatedOnDate(self.OriginalItem().CreatedOnDate);
            item.CreatedByUserID(self.OriginalItem().CreatedByUserID);
            item.LastModifiedOnDate(self.OriginalItem().LastModifiedOnDate);
            item.LastModifiedByUserID(self.OriginalItem().LastModifiedByUserID);
        }
        self.showEditor(false);
    };

	self.activeSort = self.headers[0]; //set the default sort

	self.sort = function (header, event) {
		//if this header was just clicked a second time...
		if (self.activeSort === header) {
			header.asc = !header.asc; //...toggle the direction of the sort
		} else {
			self.activeSort = header; //first click, remember it
		}
		var prop = self.activeSort.sortPropertyName;
		var ascSort = function (a, b) { return a[prop]() < b[prop]() ? -1 : a[prop]() > b[prop]() ? 1 : a[prop]() == b[prop]() ? 0 : 0; };
		var descSort = function (a, b) { return a[prop]() > b[prop]() ? -1 : a[prop]() < b[prop]() ? 1 : a[prop]() == b[prop]() ? 0 : 0; };
		var sortFunc = self.activeSort.asc ? ascSort : descSort;
		self.Items.sort(sortFunc);
	};
};

DNNDev.DNNModules.NewsBeast.Paging = function (target, pageSize) {
    var _pageSize = ko.observable(pageSize || 10), // default pageSize to 10
        _currentPage = ko.observable(1); // default current page to 1

    target.pageSize = ko.computed({
        read: _pageSize,
        write: function (newValue) {
            if (newValue > 0) {
                _pageSize(newValue);
            }
            else {
                _pageSize(10);
            }
        }
    });

    target.currentPage = ko.computed({
        read: _currentPage,
        write: function (newValue) {
            if (newValue > target.pageCount()) {
                _currentPage(target.pageCount());
            }
            else if (newValue <= 0) {
                _currentPage(1);
            }
            else {
                _currentPage(newValue);
            }
        }
    });

    target.pageCount = ko.computed(function () {
        return Math.ceil(target().length / target.pageSize()) || 1;
    });

    target.currentPageData = ko.computed(function () {
        var pageSize = _pageSize(),
            pageIndex = _currentPage(),
            startIndex = pageSize * (pageIndex - 1),
            endIndex = pageSize * pageIndex;

        return target().slice(startIndex, endIndex);
    });

    target.moveFirst = function () {
        target.currentPage(1);
    };
    target.movePrevious = function () {
        target.currentPage(target.currentPage() - 1);
    };
    target.moveNext = function () {
        target.currentPage(target.currentPage() + 1);
    };
    target.moveLast = function () {
        target.currentPage(target.pageCount());
    };

    return target;
};